import { isClient } from "@vueuse/core";
import { isElement } from "@/utils/types-check";
import type { Directive, DirectiveBinding } from "vue";


const nodeList = new Map();
let startClick: any;

if (isClient) {
	document.addEventListener("mousedown", (e) => (startClick = e));
	document.addEventListener("mouseup", (e) => {
		for (const handlers of nodeList.values()) {
			for (const { documentHandler } of handlers) {
				documentHandler(e, startClick);
			}
		}
	});
}

function createDocumentHandler(el: Element, binding: any) {
	let excludes: Array<any> = [];

	if (Array.isArray(binding.arg)) {
		excludes = binding.arg;
	} else if (isElement(binding.arg)) {
		excludes.push(binding.arg);
	}
	return function (mouseup: any, mousedown: any) {
		const popperRef = binding.instance.popperRef;
		const mouseUpTarget = mouseup.target;
		const mouseDownTarget = mousedown == null ? void 0 : mousedown.target;
		const isBound = !binding || !binding.instance;
		const isTargetExists = !mouseUpTarget || !mouseDownTarget;
		const isContainedByEl = el.contains(mouseUpTarget) || el.contains(mouseDownTarget);
		const isSelf = el === mouseUpTarget;
		const isTargetExcluded =
			(excludes.length && excludes.some((item) => (item == null ? void 0 : item.contains(mouseUpTarget)))) ||
			(excludes.length && excludes.includes(mouseDownTarget));
		const isContainedByPopper = popperRef && (popperRef.contains(mouseUpTarget) || popperRef.contains(mouseDownTarget));
		if (isBound || isTargetExists || isContainedByEl || isSelf || isTargetExcluded || isContainedByPopper) {
			return;
		}
		binding.value(mouseup, mousedown);
	};
}

/**
 * 角色权限
 */
export const clickOutSide: Directive = {
	beforeMount(el: HTMLElement, binding: DirectiveBinding) {
		if (!nodeList.has(el)) {
			nodeList.set(el, []);
		}
		nodeList.get(el).push({
			documentHandler: createDocumentHandler(el, binding),
			bindingFn: binding.value,
		});
	},

	updated(el: HTMLElement, binding: DirectiveBinding) {
		if (!nodeList.has(el)) {
			nodeList.set(el, []);
		}
		const handlers = nodeList.get(el);
		const oldHandlerIndex = handlers.findIndex((item: any) => item.bindingFn === binding.oldValue);
		const newHandler = {
			documentHandler: createDocumentHandler(el, binding),
			bindingFn: binding.value,
		};
		if (oldHandlerIndex >= 0) {
			handlers.splice(oldHandlerIndex, 1, newHandler);
		} else {
			handlers.push(newHandler);
		}
	},
	unmounted(el) {
		nodeList.delete(el);
	},
};
